import React, {useEffect, useState} from 'react';
import {CheckOutlined} from '@ant-design/icons';
import {Input, Modal, Select, Space, Switch, Tag, Tooltip, Tree} from 'antd';
import type {DataNode} from 'antd/es/tree';
import {createFileApi, deleteFileApi, exportFileZip, fileTree} from "./api";
import Counter from "../../mobx-store/index";
import MDUpload from "../../utils/upload/MDUpload";
import {DownloadMarkdownFile} from "../../utils/download";
import {createMkdir} from "../../utils/upload/api";
import FileBar from "../file-bar";

require('./index.css')


const FileTree = () => {
    const [showLine, setShowLine] = useState<boolean>(false);
    const [showLeafIcon, setShowLeafIcon] = useState<boolean | React.ReactNode>(false);
    const [myTreeData, setMyTreeData] = useState<DataNode[]>([])
    const [choosePath, setChoosePath] = useState<string>('')
    const [isFileModalOpen, setIsFileModalOpen] = useState(false);
    const [isDirModalOpen, setIsDirModalOpen] = useState(false);
    const [isDelModalOpen, setIsDelModalOpen] = useState(false);
    const [pathName, setPathName] = useState<string>('')
    const [fileVisible, setFileVisible] = useState<boolean>(false)
    const [dirVisible, setDirVisible] = useState<boolean>(false)
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>();
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>();

    /**
     * 获取文件树
     */
    const queryTreeApi = async () => {
        setMyTreeData(await fileTree())
    }
    // 定义操作后的回调函数
    const Callback = () => {
        // 1. 刷新文件树
        queryTreeApi().catch((error: any) => console.log(error));

        // 2. 恢复展开的节点
        setExpandedKeys(expandedKeys);

        // 3. 恢复选中的key
        setSelectedKeys([choosePath]);
    };


    //----------------------------------给bar的新建文件---------------------------------

    //打开
    const openFileBar = async () => {
        console.log("打开了文件")
        setFileVisible(true);
    };
    //关闭
    const closeFileBar = () => {
        console.log("关闭了文件")
        setFileVisible(false);
        Callback()
    };


    //----------------------------------给bar的新建文件夹---------------------------------
    //打开
    const openDirBar = async () => {
        console.log("打开了文件夹")
        setDirVisible(true);

    };
    //关闭
    const closeDirBar = () => {
        console.log("关闭了文件夹")
        setDirVisible(false);
        Callback()

    };


    //----------------------------------删除文件操作---------------------------------

    const deleteFile = async () => {
        await deleteFileApi(choosePath)
        handleDelCancel()
        Callback()
    }

    /**
     * 确定删除
     */
    const handleDelOk = async () => {
        await deleteFile()

    };
    //关闭弹窗
    const handleDelCancel = () => {
        setIsDelModalOpen(false);
        queryTreeApi().catch(r => console.log(r))
    };

    //----------------------------------新建文件操作---------------------------------
    /**
     * 新建文件
     */
    const createFile = async () => {
        await createFileApi(pathName, choosePath)
        setIsFileModalOpen(false);
        Callback()
    }
    /**
     * 保存
     */
    const handleOk = async () => {
        await createFile()
    };
    //关闭弹窗
    const handleCancel = () => {
        setIsFileModalOpen(false);
        queryTreeApi().catch(r => console.log(r))
    };

    // 处理输入变化的回调函数
    const handleInputChange = (e: any) => {
        const value = e.target.value; // 获取输入框的值
        setPathName(value); // 更新 pathName 的值
    };
    //----------------------------------新建文件夹操作---------------------------------

    /**
     * 新建文件夹
     */
    const createDir = async () => {
        console.log(pathName, choosePath)
        await createMkdir(pathName, choosePath)
        setIsDirModalOpen(false);
        Callback()
    }
    /**
     * 保存
     */
    const handleDirOk = async () => {
        await createDir()
    };
    //关闭弹窗
    const handleDirCancel = () => {
        setIsDirModalOpen(false);
    };

    // 处理输入变化的回调函数
    const handleDirInputChange = (e: any) => {
        const value = e.target.value; // 获取输入框的值
        setPathName(value); // 更新 pathName 的值
    };

    /**
     * ----------------------------------刷新url----------------------------------
     */
    useEffect(() => {
        if (choosePath) {
            Counter.setPath(choosePath)
        }
    }, [choosePath])
    /**
     * ----------------------------------刷新树结构数据----------------------------------
     */
    useEffect(() => {
        queryTreeApi().catch(r => console.log(r))
    }, [])


    /**
     * 选择文件
     * @param selectedKeys 选择的key
     * @param info 选择的信息
     */
    const onSelect = (selectedKeys: React.Key[], info: any) => {
        const selectNode = info.selectedNodes[0]
        console.log(selectNode ? '获取到' + selectNode.path : '没有获取到')
        if (selectedKeys[0]) {
            // 拷贝一份上次的展开的key
            setSelectedKeys(selectedKeys);
        }
        setChoosePath(selectedKeys[0] ? selectNode.path : '')
        Counter.setUrl(selectedKeys[0] ? selectNode.url : '')
        Counter.setTitle(selectedKeys[0] ? selectNode.pathName : '')
    };
    /**
     * 图标处理
     * @param value
     */
    const handleLeafIconChange = (value: 'true' | 'false' | 'custom') => {
        if (value === 'custom') {
            return setShowLeafIcon(<CheckOutlined/>);
        }
        if (value === 'true') {
            return setShowLeafIcon(true);
        }
        return setShowLeafIcon(false);
    };
    /**
     * 展开/收起节点
     */
    const onExpand = (expandedKeys: React.Key[]) => {
        console.log('onExpand', expandedKeys);
        //拷贝一份上次的展开节点
        setExpandedKeys(expandedKeys);
    }
    /**
     * 页面渲染
     */
    return (
        <div>
            <div style={{marginBottom: 10}}>
                多样化显示: <Switch checked={showLine} onChange={setShowLine}/>
                {showLine &&
                    <>
                        <br/>
                        <br/>
                        显示模式:{' '}
                        <Select defaultValue="true" onChange={handleLeafIconChange} style={{width: 70}}>
                            <Select.Option value="true">图标</Select.Option>
                            <Select.Option value="false">线</Select.Option>
                            {/*<Select.Option value="custom">Custom icon</Select.Option>*/}
                        </Select>
                    </>}
            </div>
            <FileBar
                fileVisible={fileVisible}
                fileClose={closeFileBar}
                fileOpen={openFileBar}
                dirVisible={dirVisible}
                dirOpen={openDirBar}
                dirClose={closeDirBar}
            />
            <Tree
                style={{border: '1px solid #f0f0f0', marginTop: '10px', marginRight: '5px', marginBottom: '10px'}}
                showLine={showLine ? {showLeafIcon} : false}
                onSelect={onSelect}
                onExpand={onExpand}
                treeData={myTreeData}
                fieldNames={{title: 'pathName', key: 'id', children: 'children'}}
                titleRender={(nodeData: any) => {
                    if (nodeData.children) {
                        return (
                            <>
                                <Space>
                                    {nodeData.pathName}
                                    <Tooltip placement="top" title={"新建文件"}>
                                        <Tag color="green" onClick={() => setIsFileModalOpen(true)}>
                                            文件
                                        </Tag>
                                    </Tooltip>
                                    <Tooltip placement="top" title={"新建文件夹"}>
                                        <Tag color="green" onClick={() => setIsDirModalOpen(true)}>
                                            文件夹
                                        </Tag>
                                    </Tooltip>
                                    <Tooltip placement="top" title={"删除"}>
                                        <Tag color="red" onClick={() => setIsDelModalOpen(true)}>
                                            删除
                                        </Tag>
                                    </Tooltip>
                                    <MDUpload onClose={Callback}/>
                                    <Tooltip placement="top" title={"导出文件夹"}>
                                        <Tag color="cyan" onClick={() => exportFileZip(choosePath, Counter.title)}>
                                            导出
                                        </Tag>
                                    </Tooltip>
                                </Space>
                            </>
                        );
                    } else {
                        return (
                            <>
                                <Space>
                                    {nodeData.pathName}
                                    <Tag color="red" onClick={() => setIsDelModalOpen(true)}>
                                        删除
                                    </Tag>
                                </Space>
                                <Tag color="cyan" onClick={() => DownloadMarkdownFile(Counter.url, Counter.title)}>
                                    导出
                                </Tag>
                            </>
                        );
                    }
                }}
            />
            {/*    新建文件的文件名*/}
            {isFileModalOpen &&
                <Modal title="新建文件"
                       okText={'保存设置'}
                       open={isFileModalOpen}
                       onOk={handleOk}
                       onCancel={handleCancel}>
                    <Input
                        placeholder={'新建的文件名'}
                        value={pathName}
                        onChange={handleInputChange}/>
                </Modal>}
            {/*    新建文件的文件夹*/}
            {isDirModalOpen &&
                <Modal title="新建文件夹"
                       okText={'保存设置'}
                       open={isDirModalOpen}
                       onOk={handleDirOk}
                       onCancel={handleDirCancel}>
                    <Input
                        placeholder={'新建的文件夹名'}
                        value={pathName}
                        onChange={handleDirInputChange}/>
                </Modal>}
            {/*    删除操作*/}
            {isDelModalOpen &&
                <Modal title={`确定删除"${Counter.title}"吗？`}
                       okText={'确定'}
                       open={isDelModalOpen}
                       onOk={handleDelOk}
                       onCancel={handleDelCancel}>
                </Modal>}
        </div>
    );
};

export default FileTree;
